package com.yhq.yhqproject.base.common.aop;

import com.alibaba.fastjson.JSON;

import com.yhq.yhqproject.base.common.anno.IgnoreResponseAdvice;
import com.yhq.yhqproject.base.common.web.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查注解是否存在，存在则忽略拦截
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }
        return !Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(IgnoreResponseAdvice.class);

    }

    @Override
    public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType, @NotNull MediaType selectedContentType, @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType, @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {
        // 判断请求是否来自Knife4j
        String uri = request.getURI().toString();
        if (uri.contains("/v2/api-docs")||uri.contains("/swagger-resources")) {
            return body;
        }
        if (body == null) {
            return ResultVO.success();
        }
        if (body instanceof ResultVO) {
            return body;
        }
        if (body instanceof String) {
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return JSON.toJSONString(ResultVO.success(body));
        }
        if (body instanceof LinkedHashMap) {
            LinkedHashMap<?, ?> map = (LinkedHashMap<?, ?>) body;
            int code = Integer.parseInt(map.get("status").toString());
            String msg = map.get("error").toString();

            Map<String, Object> obj = new HashMap<>();
            obj.put("uri", map.get("path"));
            obj.put("message", map.get("message"));
            return ResultVO.fail(code, msg, obj);
        }
        return ResultVO.success(body);
    }

    @ExceptionHandler(Exception.class)
    public ResultVO<?> handlerException(Exception e, HttpServletRequest request) {
        String msg;
        /**
        Map<String, Object> obj = null;

        String uri = request.getRequestURI();
        StackTraceElement[] steps = e.getStackTrace();
        StackTraceElement ste = steps[0];
        obj = new HashMap<>();
        obj.put("uri", uri);
        obj.put("className", ste.getClassName());
        obj.put("methodName", ste.getMethodName());
        obj.put("lineNumber", ste.getLineNumber());
        */
        if (e instanceof BindException) {
            BindingResult bindingResult = ((BindException) e).getBindingResult();
            StringBuilder sb = new StringBuilder();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                sb.append(fieldError.getField()).append(" ：").append(fieldError.getDefaultMessage()).append(" ");
            }
            msg = sb.toString();
        } else {
            msg = e.getMessage();
        }
        log.error(msg);
        return ResultVO.fail(500, msg, null);
    }


}
